package top.kikt.handledeletemedia

import android.Manifest
import android.database.ContentObserver
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import androidx.core.database.getStringOrNull
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var permissionResult = false

    val tag = "My-Tag"

    private val ob = Ob()

    private var registered = false;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button_request_permission.setOnClickListener {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                2000
            )
        }

        bt_observer.setOnClickListener {
            checkPermission {
                if (registered) {
                    return@checkPermission
                }
                registered = true
                contentResolver.registerContentObserver(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    true,
                    ob
                )
            }
        }

        bt_observer.setOnClickListener {
            checkPermission {
                if (registered) {
                    return@checkPermission
                }
                registered = true
                contentResolver.registerContentObserver(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    true,
                    ob
                )
            }
        }

        bt_unregister.setOnClickListener {
            checkPermission {
                if (!registered) {
                    return@checkPermission
                }
                registered = false
                contentResolver.unregisterContentObserver(ob)
            }
        }

        bt_scan.setOnClickListener {
            checkPermission {
                scan()
            }
        }
    }

    private fun scan() {
        val cursor = contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )

        cursor?.use {
            val columnCount = cursor.columnCount

            while (cursor.moveToNext()) {
                val sb = StringBuilder()
                for (i in 0 until columnCount) {
                    val name = cursor.getColumnName(i)
                    val value = cursor.getStringOrNull(i)
                    sb.append("$name : $value \n")
                }
                Log.i(tag, sb.toString())
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 2000) {
            permissionResult = grantResults.any {
                it == PERMISSION_GRANTED
            }

            Log.i(tag, "result = $permissionResult")
        }
    }

    inline fun checkPermission(run: () -> Unit) {
        if (permissionResult) {
            run()
        } else {
            Log.i(tag, "权限没申请")
        }
    }

    inner class Ob(private val handler: Handler = Handler(Looper.getMainLooper())) :
        ContentObserver(handler) {

        override fun onChange(selfChange: Boolean, uri: Uri?) {
            super.onChange(selfChange, uri)
            Log.i(tag, "发生变化 = $uri")

            if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) {
                Log.i(tag, "uri 为总uri $uri, 应该是删除")
                return
            }

            if (uri == null) {
                return
            }
            val cursor = contentResolver.query(uri, null, null, null, null)
            if (cursor == null) {
                Log.i(tag, "cursor is null")
                return
            }
            cursor.use {
                Log.i(tag, "cursor 数量 = ${cursor.count}")
                if (cursor.count == 0) {
                    Log.i(tag, "cursor没数据")
                    return
                }

                while (cursor.moveToNext()) {
                    val names = it.columnNames
                    names.forEach { name ->
                        val index = cursor.getColumnIndex(name)
                        val value = cursor.getStringOrNull(index)
                        Log.i(tag, "$name : ${value ?: "null"}")
                    }
                }
            }
        }
    }
}
